#! /usr/bin/python
# -*- coding: utf-8 -*-

class Tag:
    def __init__(self, node, tagconfig, htmlEncodingMode=False, stripTagMode=False):
        self.node = node
        self.tagconfig = tagconfig
        self.htmlEncodingMode = htmlEncodingMode
        self.stripTagMode = stripTagMode
    def renderStartTag(self):
        if self.stripTagMode:
            return ''
        nodeName = self.node.nodeName
        startTag = self.htmlEncode('<') + nodeName
        attrs = self.node.attributes
        if attrs:
            for attr in attrs.items():
                attrName = attr[0]
                attrValue = attr[1]
                if attrName in self.tagconfig['commonAttributes']:
                    validatorClass = self.tagconfig['commonAttributes'][attrName]['validatorClass']
                    aValidator = validatorClass(attrValue)
                    startTag += ' ' + attrName + '=' + self.htmlEncode('\"') + aValidator.filter() + self.htmlEncode('\"')
                else:
                    nodeConfig = self.getNodeConfig()
                    if nodeConfig and 'attributes' in nodeConfig:
                        if attrName in nodeConfig['attributes']:
                            validatorClass = nodeConfig['attributes'][attrName]['validatorClass']
                            if attrName == 'style':
                                validStyles = nodeConfig['attributes'][attrName]['validStyles']
                                aValidator = validatorClass(attrValue, validStyles)
                            else:
                                aValidator = validatorClass(attrValue)
                            startTag += ' ' + attrName + '=' + self.htmlEncode('\"') + aValidator.filter() + self.htmlEncode('\"')
        startTag += self.htmlEncode('>')
        return startTag
    def renderEndTag(self):
        if self.stripTagMode:
            return ''
        return self.htmlEncode('<') + '/' + self.node.nodeName + self.htmlEncode('>')
    def getNodeConfig(self):
        return None
    def htmlEncode(self, char):
        encodingMap = {
            '<':'&lt;',
            '>':'&gt;',
            '"':'&quot;'
        }
        encoded = char
        if self.htmlEncodingMode and char in encodingMap:
            encoded = encodingMap[char]
        return encoded

class HtmlTag(Tag):
    def getNodeConfig(self):
        return self.tagconfig['htmlTags'][self.node.nodeName]

class MathTag(Tag):
    def getNodeConfig(self):
        return self.tagconfig['mathmlTags'][self.node.nodeName]
    def htmlEncode(self, char):
        encodingMap = {
            '<':'&amp;lt;',
            '>':'&amp;gt;',
            '"':'&amp;quot;'
        }
        encoded = char
        if self.htmlEncodingMode and char in encodingMap:
            encoded = encodingMap[char]
        return encoded

class RootTag(HtmlTag):
    def renderStartTag(self):
        return ''
    def renderEndTag(self):
        return ''
